# coding:utf-8
"""
    Author: walrus
    Date: 2024/11/6
    File: 1.1.py
"""

# 列表推导式
my_list = [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
values = [d['key2'] for d in my_list if 'key2' in d]
print(values)

people = [{'name': 'Alice', 'age': 25},
          {'name': 'Bob', 'age': 30},
          {'name': 'Charlie', 'age': 28}]
names = [person['name'] for person in people]
print(names)

# 循环遍历
my_list = [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
values2 = []
for d in my_list:
    if 'key2' in d:
        values2.append(d['key2'])
print(values2)

# filter和lambda函数
my_list = [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
values = list(filter(lambda d: 'key2' in d, my_list))
values = [d['key2'] for d in values]
print(values)

# map和get
"""
    尝试访问一个不存在的键将会导致`KeyError`，
    因此可以使用`dict.get()`方法来获取一个默认值，从而避免这一错误
"""
my_list = [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
values = list(map(lambda d: d.get('key2', "None"), my_list))
print(values)